<template>
  <page-wrap
    back
    hide-tab
    title="职业测评"
    class="pageWrap"
    stayStill
    :bgColor="topBg"
  >
    <view class="container">
      <view class="top_fixed">
        <view class="top_progress">
          <u-line-progress
            class="progress"
            inactive-color="#CFE1C3"
            active-color="#79D9BA"
            :show-percent="false"
            :percent="questionPercent"
          ></u-line-progress>
          <!-- <text class="progress_text">{{ questionPercent }}%</text> -->
          <text class="progress_text"
            >{{ answeredNumber }}/{{ totalNumber }}</text
          >
        </view>
        <view class="top_container">
          <view class="top_container_tips">选择的时候尽可能不要选择中立~</view>
        </view>
      </view>
      <view class="quest">
        <!-- 菲报错 语法提示 前端说不用管-->
        <questionOneStyleListItem
          v-if="questionType == 0"
          v-for="(item, index) in list"
          :key="item.id"
          :itemIndex="index"
          :itemObj="item"
          :borderIndex="list.length - 1 != index"
          @clickBack="getSelectIndex"
        />
        <questionTwoStyleSingleItem
          v-if="questionType == 1"
          :itemObj="ItemObj"
          @clickBack="getSelectAnswer"
        />
        <questionThreeStyleMusicItem
          v-if="questionType == 2"
          :itemObj="ItemObj"
          @clickBack="getSelectAnswer"
        />
        <questionFourStylePictureItem
          v-if="questionType == 3"
          :itemObj="ItemObj"
          @clickBack="getSelectAnswer"
        />
      </view>
    </view>
    <view class="bottom_fixed">
      <view class="bottom_btn_one" v-if="questionIndex < 5">
        <view class="bottom_btn_one_next_btn" @click="handleNextBtn">
          下一页
        </view>
      </view>
      <view
        class="bottom_btn_two"
        v-else-if="questionIndex >= totalList.length - 4"
      >
        <view class="bottom_btn_two_last_btn" @click="handleLastBtn">
          上一页
        </view>
        <view class="bottom_btn_two_next_btn" @click="handleCommit">
          领取神兽
        </view>
      </view>
      <view class="bottom_btn_three" v-else>
        <view class="bottom_btn_three_last_btn" @click="handleLastBtn">
          上一页
        </view>
        <view class="bottom_btn_three_next_btn" @click="handleNextBtn">
          下一页
        </view>
      </view>
    </view>
  </page-wrap>
</template>

<script>
import questionOneStyleListItem from './questionOneStyleListItem.vue';
import questionTwoStyleSingleItem from './questionTwoStyleSingleItem.vue';
import questionThreeStyleMusicItem from './questionThreeStyleMusicItem.vue';
import questionFourStylePictureItem from './questionFourStylePictureItem.vue';
import {
  checkStatus,
  questionList,
  submitAnswer,
  calculateResult
} from '@/api/modules/activity';
import { getUserInfo, createQR } from '@/api/modules/career';
import ShareMixin from '@/mixins/share';
export default {
  components: {
    questionOneStyleListItem,
    questionTwoStyleSingleItem,
    questionThreeStyleMusicItem,
    questionFourStylePictureItem
  },
  mixins: [ShareMixin],
  data() {
    return {
      personId: uni.getStorageSync('person-id').slice(2) || undefined,
      resultId: 0,
      topBg: '#eaf9e1',
      questionType: 0,
      questionIndex: 0,
      list: [],
      ItemObj: {},
      totalList: [],
      questionPercent: 0,
      sharePath: '/pagesSub/career/activity/vocationalAssessment', // 分享自定义路径
      shareTitle: '职业测评',
      imageUrl:
        'https://img3.job1001.com/ypMp/elan/images/career/vocationalAssessmentQuestion/share_cover.jpg',
      answeredNumber: 0,
      totalNumber: 0,
      fromWhere: '',
      fromSxh: '',
      assessmentType: '',
      assessmentVersion: uni.getStorageSync('assessmentVersion')
    };
  },
  onLoad(opt) {
    this.fromWhere = opt.fromWhere || '';
    this.fromSxh = opt.fromSxh || '';
    if (this.fromWhere == 'junior') {
      this.assessmentType = '1';
    }
  },
  created() {
    this.resultId = wx.getStorageSync('assessmentId');
    this.reqQuestionList();
  },
  methods: {
    async createQRFn() {
      const params = {
        fromPersonId: uni.getStorageSync('SxhPersonId'),
        valueId: this.resultId,
        rightId: 2,
        shareUrl: 'pagesSub/doubleChannelChoosingMeeting/qrCodeParse',
        cardType: uni.getStorageSync('cardType')
      };
      const res = await createQR(params);
      if (res.code == 200) {
        uni.navigateTo({
          url:
            '/pagesSub/doubleChannelChoosingMeeting/qrCodeResult?from=vocationalAssessmentAnswer' +
            '&qrCodeText=扫码查看保留职业测评结果' +
            '&buttonText=立即查看结果(不保留)' +
            '&qrcodeUrl=' +
            res.data.qRImageBase64
        });
      }
    },
    //获取问题列表
    reqQuestionList() {
      const params = {
        resultId: this.resultId
      };
      uni.showLoading();
      questionList(params).then((res) => {
        if (res.code == 200) {
          this.totalList = res.data;
          if (!this.totalList || this.totalList.length == 0) return;
          this.totalNumber = this.totalList.length;
          this.list = this.totalList.slice(
            this.questionIndex,
            this.questionIndex + 5
          );
          this.calPercentprogress();
          uni.hideLoading();
        } else {
          uni.showToast({
            title: res.status_desc,
            icon: 'none',
            duration: 2000
          });
        }
      });
    },
    //用户答题提交答案
    reqSubmitAnswer(questionId, answerValue) {
      const params = {
        resultId: this.resultId,
        questionId: questionId,
        answerValue: answerValue
      };
      // console.log(params);
      submitAnswer(params).then((res) => {
        if (res.code == 200) {
          this.calPercentprogress();
        } else {
          uni.showToast({
            title: res.status_desc,
            icon: 'none',
            duration: 2000
          });
        }
      });
    },
    //完成测评答题计算结果
    reqCalculateResult() {
      const params = {
        personId: this.personId,
        resultId: this.resultId,
        assessmentType: this.assessmentType
      };
      uni.showLoading();
      calculateResult(params).then((res) => {
        if (
          res.code == 200 ||
          (res.code == 201 && res.status_desc == '答卷已完成！')
        ) {
          // 跳转到中学生职途结果页
          if (this.assessmentType == '1') {
            uni.redirectTo({
              url: `/pagesSub/career/activity/JuniorCareerAssessResult?fromWhere=${this.fromWhere}&fromSxh=${this.fromSxh}`
            });
          } else {
            if (this.fromSxh == 'sxh') {
              // 如果是来自双选会的首页，就跳到二维码页面
              this.createQRFn();
            } else {
              // 如果不是，就直接跳到结果页面
              uni.redirectTo({
                url: `/pagesSub/careerAssessResultActNew/index?fromWhere=${this.fromWhere}&fromSxh=${this.fromSxh}`
              });
            }
          }
          uni.hideLoading();
        } else {
          uni.showToast({
            title: res.status_desc,
            icon: 'none',
            duration: 2000
          });
        }
      });
    },
    //计算百分比进度
    calPercentprogress() {
      if (this.totalList.length != 0) {
        this.answeredNumber = 0;
        for (let i = 0; i < this.totalList.length; i++) {
          let questionAnswer = this.totalList[i].questionAnswer;
          if (questionAnswer) {
            var percent = i / (this.totalList.length - 1);
            this.questionPercent = Math.round(percent * 100);
            this.answeredNumber++;
          }
        }
      }
    },
    getSelectIndex({ questionId, answerValue, itemIndex }) {
      this.list[itemIndex].questionAnswer = answerValue;
      this.reqSubmitAnswer(questionId, answerValue);
      // console.log(
      //   "this.totalList",
      //   this.totalList,
      //   "this.questionIndex",
      //   this.questionIndex
      // );
    },
    getSelectAnswer({ questionId, answerValue, itemObj }) {
      this.ItemObj = itemObj;
      this.totalList[this.questionIndex].questionAnswer = answerValue;
      // console.log(
      //   "getSelectAnswerItemObj",
      //   this.ItemObj,
      //   "this.questionIndex",
      //   this.questionIndex
      // );
      this.reqSubmitAnswer(questionId, answerValue);
    },
    //上一页
    handleLastBtn() {
      //滑动到顶部题目处
      uni.pageScrollTo({
        scrollTop: 0,
        duration: 0
      });
      if (this.questionType == 0) {
        this.list = this.totalList.slice(
          this.questionIndex - 5,
          this.questionIndex
        );
        this.questionIndex = this.questionIndex - 5;
      } else if (this.questionType == 1 && this.questionIndex == 60) {
        // this.questionType = 0;
        // this.questionIndex = this.questionIndex - 5;
      } else {
        this.questionIndex--;
        this.ItemObj = this.totalList.slice(
          this.questionIndex,
          this.questionIndex + 1
        )[0];
        this.questionType = this.ItemObj.questionType;
      }
    },
    //下一页
    handleNextBtn() {
      //校验当前页题目是否答完 答完才能进入下一页
      let flag = true;
      if (this.questionType == 0) {
        if (this.questionIndex <= 55) {
          this.list.forEach((item) => {
            if (!item.questionAnswer) {
              flag = false;
            }
          });
        }
        if (!flag) {
          uni.showToast({ icon: 'none', title: '请先完成当前页题目' });
          return;
        }
        this.questionIndex = this.questionIndex + 5;
        // console.log("questionIndex", this.questionIndex);
      } else {
        //附加题未填
        if (!this.ItemObj.questionAnswer) {
          flag = false;
        }
        if (!flag) {
          uni.showToast({ icon: 'none', title: '请先完成当前页题目' });
          return;
        }
      }
      //滑动到顶部题目处
      uni.pageScrollTo({
        scrollTop: 0,
        duration: 0
      });

      if (this.questionType == 0) {
        // if (this.questionIndex >= 60) {
        //   this.ItemObj = this.totalList.slice(
        //     this.questionIndex,
        //     this.questionIndex + 1
        //   )[0];
        //   this.questionType = this.ItemObj.questionType;
        //   return;
        // }
        this.list = this.totalList.slice(
          this.questionIndex,
          this.questionIndex + 5
        );
      } else {
        this.questionIndex++;
        this.ItemObj = this.totalList.slice(
          this.questionIndex,
          this.questionIndex + 1
        )[0];
        this.questionType = this.ItemObj.questionType;
      }
    },
    // //返回上一页面
    // handleExit() {
    //   uni.navigateBack({
    //     delta: 1,
    //   });
    // },
    //领取神兽
    async handleCommit() {
      //查询职途卡信息
      await getUserInfo({ uid: '' });
      this.reqCalculateResult();
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  background-color: #eaf9e1;
  min-height: calc(100vh - 272rpx);
}

.top_container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 26rpx;
}

.top_container_tips {
  color: #8fbe73;
  font-size: 24rpx;
}

.top_fixed {
  position: fixed;
  background: #eaf9e1;
  width: 100%;
  padding-left: 32rpx;
  padding-right: 32rpx;
}

.top_progress {
  display: flex;
  flex-direction: row;
}

.progress {
  flex: 1;
  width: 95%;
}

.progress_text {
  margin-left: 16rpx;
  font-size: 28rpx;
  color: #000000;
}

.quest {
  padding-top: 86rpx;
  padding-bottom: 130rpx;
}

.bottom_fixed {
  width: 100%;
  height: 250rpx;
  position: fixed;
  bottom: 0;
  background-image: url($img-base + 'career/vocationalAssessmentQuestion/question_bg_bottom.png');
  background-size: 100% 100%;
}

.bottom_btn_one {
}

.bottom_btn_one_next_btn {
  width: 80%;
  height: 88rpx;
  color: #ffffff;
  bottom: 75rpx;
  left: 50%;
  position: absolute;
  transform: translateX(-50%);
  text-align: center;
  background: #15c297;
  border-radius: 44rpx;
  line-height: 88rpx;
}

.bottom_btn_two {
  display: flex;
  justify-content: row;
  padding-left: 50rpx;
  padding-right: 50rpx;
  padding-top: 80rpx;
}

.bottom_btn_two_last_btn {
  flex: 1;
  width: 40%;
  height: 88rpx;
  color: #ffffff;
  text-align: center;
  background: #15c297;
  border-radius: 44rpx;
  line-height: 88rpx;
}

.bottom_btn_two_next_btn {
  flex: 2;
  width: 40%;
  height: 88rpx;
  color: #ffffff;
  text-align: center;
  margin-left: 20rpx;
  background: #f75a3e;
  border-radius: 44rpx;
  line-height: 88rpx;
}

.bottom_btn_three {
  display: flex;
  justify-content: row;
  padding-left: 50rpx;
  padding-right: 50rpx;
  padding-top: 80rpx;
}

.bottom_btn_three_last_btn {
  flex: 1;
  width: 40%;
  height: 88rpx;
  color: #ffffff;
  text-align: center;
  background: #15c297;
  border-radius: 44rpx;
  line-height: 88rpx;
}

.bottom_btn_three_next_btn {
  flex: 2;
  width: 40%;
  height: 88rpx;
  color: #ffffff;
  text-align: center;
  margin-left: 20rpx;
  background: #15c297;
  border-radius: 44rpx;
  line-height: 88rpx;
}
</style>
